<template>
  <a-spin :spinning="Data.spinning" tip="数据处理中，请耐心等待……">
    <div class="subject-manage-container">
      <a-card class="layout-card">
        <a-row align="middle" justify="space-between">
          <div class="flex justify-between">
            <SearchGroup
              :label-option="labelOption"
              @handleSearch="loadData(1)"
              @handle-reset="reset"
              :searchOption="filterOption"
            />
            <div class="">
              <scoreStat v-model:spinning="Data.spinning" v-if="userInfo.accountType == 'ADMIN'" />
              <scoreStat
                v-model:spinning="Data.spinning"
                :zpDataFlag="true"
                v-if="userInfo.accountType == 'ADMIN'"
              />
              <a-button
                type="primary"
                class="ml-2"
                v-if="userInfo.accountType == 'ADMIN'"
                @click="handleTogether()"
              >
                成绩归档
              </a-button>
              <a-button
                type="primary"
                class="ml-2"
                v-if="userInfo.accountType == 'ADMIN'"
                @click="handleKsCjInfother()"
              >
                导出成绩
              </a-button>
            </div>
          </div>
          <a-col style="display: flex">
            <!-- <a-button class="btn" type="primary" v-if="route.meta?.buttonList?.includes('SubjectManageAdd')"
            @click="handleAdd"><plus-outlined />新建</a-button>
          <a-upload :showUploadList="Data.showUploadList" v-model:file-list="Data.fileList" accept=".xlsx, .xls, .dbf" name="file"
            :customRequest="customRequest" v-if="route.meta?.buttonList?.includes('SubjectManageImporOperate')"><a-button
              class="btn" type="primary">导入</a-button>
          </a-upload>


          <a-button class="btn" type="primary" @click="handleAllEdit"
            v-if="route.meta?.buttonList?.includes('pyHandle')">评阅批量设置</a-button>
          <a-button class="btn" v-if="route.meta?.buttonList?.includes('SubjectManageDelete')" type="primary" danger
            @click="handleDel">删除所选科目</a-button> -->
          </a-col>
        </a-row>
        <!-- :row-selection="{ selectedRowKeys: Data.selectedRowKeys, onChange: onSelectChange }" -->
        <a-table
          class="tablstyle"
          rowKey="id"
          :scroll="{ x: 1450 }"
          bordered
          :loading="loading"
          :pagination="false"
          :dataSource="list"
          :columns="columns"
          :row-class-name="
            (record, index) => {
              if (!record?.statistics?.pywcRate) return 'bg-red-200'
              if (record?.statistics?.pywcRate < 1) return 'bg-orange-200'
              return 'bg-green-200'
            }
          "
        >
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'pywc'">
              <div class="py-5">
                <a-progress
                  stroke-color="#10C0B6"
                  :percent="Number(record?.statistics?.pywcRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-green-600"> {{ record?.statistics?.pywcNum || 0 }} </i>/
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'pyz'">
              <div class="py-5">
                <a-progress
                  stroke-color="#F97316"
                  :percent="Number(record?.statistics?.pyzRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-orange-600"> {{ record?.statistics?.pyzNum || 0 }} </i> /
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>
            <template v-if="column.dataIndex === 'wpy'">
              <div class="py-5">
                <a-progress
                  stroke-color="#DC2626"
                  :percent="Number(record?.statistics?.wpyRate || 0) * 100"
                  :format="percent => `${percent.toFixed(2)}%`"
                />
              </div>
              <span>
                <i class="text-red-600"> {{ record?.statistics?.wpyNum || 0 }} </i> /
                {{ record?.statistics?.ysmKsNum || 0 }}
              </span>
            </template>

            <template v-if="column.dataIndex == 'index'">
              {{ (curPage - 1) * pageSize + (index + 1) }}
            </template>
            <template v-if="column.dataIndex == 'operation'">
              <a-button
                type="link"
                size="small"
                v-if="route.meta?.buttonList?.includes('SubjectManageAllocationGroupLeader')"
                @click="showAllotLeaderModal(record)"
              >
                分配组长
              </a-button>

              <a-button
                type="link"
                size="small"
                v-if="route.meta?.buttonList?.includes('SubjectManageAllocationTeacher')"
                style="color: #00baad"
                @click="showAllotModal(record)"
              >
                分配评阅教师
              </a-button>
              <scoreStat
                v-if="route.meta?.buttonList?.includes('KgtScoreComputeAndApply')"
                buttonType="link"
                buttonSize="small"
                v-model:spinning="Data.spinning"
                :record="record"
              />
              <scoreStat
                v-if="route.meta?.buttonList?.includes('KgtScoreComputeAndApply')"
                buttonType="link"
                buttonSize="small"
                :record="record"
                v-model:spinning="Data.spinning"
                :zpDataFlag="true"
              />
              <a-button
                type="link"
                size="small"
                v-if="route.meta?.buttonList?.includes('KsZdfSave')"
                @click="handleTogether(record)"
              >
                成绩归档
              </a-button>
              <a-button
                type="link"
                size="small"
                v-if="route.meta?.buttonList?.includes('ExportKsCjInfo')"
                @click="handleKsCjInfother(record)"
              >
                导出成绩
              </a-button>
              <!-- <a-button type="link" v-if="route.meta?.buttonList?.includes('SubjectManageEdit')"
              @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button type="link" v-if="route.meta?.buttonList?.includes('SubjectManageDelete')" danger
              @click="handleDel(record)">
              删除
            </a-button> -->

              <a-button
                type="link"
                v-if="userInfo.accountType == 'ADMIN'"
                :disabled="record.pyOverApplyInfo?.applyState != 'AUDIT'"
                @click="handleAudit(record)"
              >
                评阅完成审核
              </a-button>
            </template>
          </template>
        </a-table>
        <a-pagination
          class="pagination"
          :show-total="total => `共 ${total} 条`"
          :show-size-changer="false"
          show-quick-jumper
          v-model:current="curPage"
          v-model:pageSize="pageSize"
          :total="total"
        />
        <AddSubject
          v-if="Data.addVisible"
          :visible="Data.addVisible"
          @refresh="loadData"
          @cancel="handleCancel"
          :addSubjectForm="Data.addSubjectForm"
        />
        <!-- 分配教师 -->
        <distributionTeacher
          v-model:allotVisible="Data.allotVisible"
          :curSubject="Data.curSubject"
        />
        <!-- 分配组长 -->
        <distributionGroupLeader
          v-model:allotVisible="Data.allotLeaderVisible"
          :curSubject="Data.curSubject"
          @success="loadData"
        />

        <!-- 评阅批量设置 -->
        <allsetstate
          v-if="Data.addAllVisible"
          :visible="Data.addAllVisible"
          @refresh="loadData"
          @cancel="handleCancel"
        />

        <!-- 审核 -->
        <auditOver
          v-model:auditVisible="Data.auditVisible"
          :auditRow="Data.auditRow"
          @success="loadData"
        />
      </a-card>
    </div>
  </a-spin>
</template>
<script lang="ts" setup>
import { statusEnum } from '/@/enums/privateEnums'
import { h, onMounted, ref, computed, reactive } from 'vue'
import scoreStat from '/@/views/home/index/components/scoreStat.vue'
import {
  deleteSubjectById,
  getSubjectList,
  autoHandleJdByKmdmAndYear,
  HandleJdByCjInfo,
  getKmPyProcess,
} from '/@/api/organization/subjectManage'
import { useList } from '/@/hooks/web/useList'
import { useMessage } from '/@/hooks/web/useMessage'
import AddSubject from './addSubject.vue'
import distributionTeacher from './distributionTeacher.vue'
import distributionGroupLeader from './distributionGroupLeader.vue'
import auditOver from './auditOver.vue'
import allsetstate from './allsetstate.vue'
import { uploadApi } from '/@/api/sys/upload'
import { useUserStore } from '/@/store/modules/user'
import { useRoute } from 'vue-router'
import { getCollegeList } from '/@/api/organization/collegeManage'
import { downloadByUrl } from '/@/utils/file/download'
import aTag from 'ant-design-vue/es/tag'
import { getDictionaryList } from '/@/views/teacher/home/index'
const route = useRoute()
const userStore = useUserStore()
const userInfo = computed<any>(() => userStore.getUserInfo)
const { createConfirm, createMessage } = useMessage()

const auditList = ref<any[]>([])
const columns = ref([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    fixed: true,
  },
  {
    title: '科目名称',
    dataIndex: 'kmmc',
    key: 'kmmc',
    align: 'center',
    width: 180,
    customRender: ({ record }) => {
      if (!record.kmdm) return ''
      return `${record.kmdm || ''}(${record.kmmc || ''})`
    },
  },
  {
    title: '所属学院',
    dataIndex: 'xymc',
    width: 180,
    key: 'xymc',
    align: 'center',
    customRender: ({ record }) => {
      if (!record.xymc) return ''
      return `${record.xydm || ''}(${record.xymc || ''})`
    },
  },
  {
    title: '评阅组长',
    width: 180,
    dataIndex: 'pyzzAccount',
    key: 'pyzzAccount',
    customRender: ({ record }) => {
      if (!record.pyzzAccount) return '--'
      return `(${record.pyzzName})${record.pyzzAccount}`
    },
    align: 'center',
  },
  {
    title: '评阅已完成',
    dataIndex: 'pywc',
    key: 'pywc',
    align: 'center',
    width: 180,
  },
  {
    title: '评阅中',
    dataIndex: 'pyz',
    key: 'pyz',
    align: 'center',
    width: 180,
  },
  {
    title: '未评阅',
    dataIndex: 'wpy',
    key: 'wpy',
    align: 'center',
    width: 180,
  },
  {
    title: '科目总分数',
    dataIndex: 'sjzf',
    key: 'sjzf',
    align: 'center',
    width: 120,
  },
  {
    title: '评阅阶段',
    dataIndex: 'pyjd',
    key: 'pyjd',
    align: 'center',
    width: 100,
    customRender: ({ text }) => {
      return statusEnum[text] || '--'
    },
  },
  {
    title: '评阅完成状态',
    dataIndex: 'pyOverApplyInfo',
    key: 'pyOverApplyInfo',
    align: 'center',
    width: 120,
    customRender: ({ text }) => {
      return text
        ? h(
            aTag,
            {
              color:
                text?.applyState == 'AUDIT'
                  ? '#F97316'
                  : text?.applyState == 'REJECT'
                  ? '#DC2626'
                  : text?.applyState == 'PASS'
                  ? '#10C0B6'
                  : '',
            },
            auditList.value.find(item => item.value === text?.applyState)?.label || '--'
          )
        : '--'
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    align: 'center',
    width: 350,
    fixed: 'right',
  },
])

const Data = reactive({
  curSubject: {},
  allotVisible: false,
  allotLeaderVisible: false,
  addVisible: false,
  addAllVisible: false,
  addSubjectForm: {},
  selectedRowKeys: [],
  loading: false,
  showUploadList: false,
  fileList: [],
  spinning: false,
  auditRow: {},
  auditVisible: false,
})

const collegeList = ref<any[]>([])

const labelOption = ref([
  { name: '科目代码', key: 'kmdm', labelWidth: 80, inputWidth: 180 },
  {
    name: '学院代码',
    key: 'xydm',
    labelWidth: 80,
    type: 'Select',
    selectOption: collegeList,
    inputWidth: 180,
  },
  {
    name: '评阅阶段',
    key: 'pyjd',
    labelWidth: 80,
    selectOption: [
      {
        label: '录入试卷',
        value: 'ENTERING',
      },
      {
        label: '试评进行中',
        value: 'TEST',
      },
      {
        label: '试评阅完成',
        value: 'OVER_TEST',
      },
      {
        label: '试评终止',
        value: 'TEST_BREAK',
      },
      {
        label: '正评进行中',
        value: 'FORMAL',
      },
      {
        label: '正评阅完成',
        value: 'OVER_FORMAL',
      },
    ],
    inputWidth: 180,
  },
])

const { reset, loadData, filterOption, curPage, total, pageSize, list, loading } = useList(
  getSubjectList,
  {
    requestSuccess() {
      getKmApplyOverview()
    },
  }
)

function getKmApplyOverview() {
  if (list.value?.length == 0) return
  let todoList = list.value.map(item => item.kmdm) || []
  getKmPyProcess({
    todoList,
  }).then(res => {
    if (res.code == 200 && list.value?.length)
      for (let i = 0; i < list.value.length; i++) {
        list.value[i].statistics = {}
        for (let j = 0; j < res.data.length; j++) {
          if (list.value[i].kmdm == res.data[j].kmdm) {
            list.value[i].statistics = res.data[j]
            break
          }
        }
      }
  })
}

const onSelectChange = keys => {
  Data.selectedRowKeys = keys
}

const handleCancel = () => {
  Data.addSubjectForm = {}
  Data.addVisible = false
  Data.addAllVisible = false
}

const handleDel = row => {
  let ids: any[]
  if (Object.prototype.toString.call(row) !== '[object Object]') {
    if (!Data.selectedRowKeys.length) {
      return createMessage.warning('您还没有选择学院！')
    }
    ids = Data.selectedRowKeys
  } else {
    ids = [row.id]
  }
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '您确定删除所选学院吗？'),
    onOk: async () => {
      const { code } = await deleteSubjectById(ids)
      if (code === 200) {
        createMessage.success('删除成功！')
        loadData()
      }
    },
  })
}

const handleTogether = (record: any = {}) => {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () =>
      h(
        'span',
        `您确定对${
          record.kmdm ? `科目'${record.kmdm}(${record.kmmc})'` : "'全部科目'"
        }的进行归档吗？`
      ),
    onOk: async () => {
      Data.spinning = true
      autoHandleJdByKmdmAndYear({
        kmdm: record.kmdm,
      })
        .then(res => {
          if (res.code == 200) {
            createMessage.success('处理完成')
          } else {
            createMessage.error(res.message)
          }
        })
        .finally(() => {
          Data.spinning = false
        })
    },
  })
}

function handleKsCjInfother(record: any = {}) {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () =>
      h(
        'span',
        `您确定导出${record.kmdm ? `科目'${record.kmdm}(${record.kmmc})'` : "'全部科目'"}的成绩吗`
      ),
    onOk: async () => {
      Data.spinning = true
      HandleJdByCjInfo({ kmdm: record.kmdm })
        .then(data => {
          const url = window.URL.createObjectURL(data)
          downloadByUrl({
            url,
            fileName: record.kmmc ? `${record.kmdm}(${record.kmmc})成绩` : '全部科目成绩',
          })
        })
        .finally(() => {
          Data.spinning = false
        })
    },
  })
}

const handleEdit = row => {
  row.zjlsIds = []
  row.teacherOptions = []
  if (row.zjlsList) {
    row.zjlsList.forEach(v => {
      if (v.jsxm.indexOf(v.account) < 0) {
        v.jsxm = `(${v.jsxm})${v.account}`
      } else {
        v.jsxm = v.jsxm
      }
      row.zjlsIds.push(v.userId)
    })
    row.teacherOptions = [...row.zjlsList]
  }
  if (row.kmzzGhAndMz && !row.zjlsIds.includes(row.kmzzId)) {
    row.teacherOptions.push({ jsxm: row.kmzzGhAndMz, userId: row.kmzzId })
  }
  Data.addSubjectForm = row
  Data.addVisible = true
}

// 批量评阅设置
const handleAllEdit = () => {
  Data.addAllVisible = true
}

const handleAdd = () => {
  Data.addSubjectForm = {
    fpCountType: 'RATIO',
  }
  Data.addVisible = true
}

// 打开分配教师弹窗
const showAllotModal = async row => {
  Data.curSubject = row
  Data.allotVisible = true
}

// 分配教师 教师下拉框筛选

// 打开分配组长弹窗
const showAllotLeaderModal = row => {
  Data.allotLeaderVisible = true
  Data.curSubject = row
}

// 导入科目
const customRequest = file => {
  const fileNames = file.file.name.split('.')
  const fileType = fileNames[fileNames.length - 1].toLocaleLowerCase()
  if (fileType != 'dbf' && fileType != 'xlsx' && fileType != 'xls') {
    createMessage.warning('只能上传.xlsx、.xls或.dbf类型的文件！')
    Data.showUploadList = false
    return
  }
  file.year = userInfo.value.kmYear
  uploadApi(`/kmxx/importKmxxInfo/${userInfo.value.kmYear}`, file).then((res: any) => {
    if (res.data.code === 200) {
      createMessage.success('上传文件成功')
      loadData()
    } else {
      createMessage.success(res.data.message)
    }
    Data.showUploadList = false
  })
}

// 学院列表

const getCollegeOption = async () => {
  try {
    const { data } = await getCollegeList({
      pageNum: 0,
      pageSize: 9999,
    })
    data.forEach(ele => {
      ele.codeName = `${ele.xydm}(${ele.xymc})`
      ele.value = ele.xydm
      ele.label = ele.codeName
    })
    collegeList.value = data.sort((a, b) => a.xydm - b.xydm)
  } catch (error) {
    console.log(error)
  }
}

function handleAudit(row: any = {}) {
  Data.auditRow = row
  Data.auditVisible = true
}

onMounted(async () => {
  getCollegeOption()
  auditList.value = (await getDictionaryList('audit')) || []
})
</script>
<style lang="less" scoped>
.subject-manage-container {
  // height: @c_height;
}

.layout-card {
  border-radius: 8px;
}

.tablstyle {
  padding: 15px 0;
}

.btn {
  margin-left: 20px;
}

.allot-modal {
  padding: 0 20px;
}

.abnormal-modal {
  padding: 20px;
}

.abnormal-content {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
}

.abnormal-item {
  display: flex;
  align-items: center;
  margin: 0 20px 12px 0;
}

.allotTitle {
  padding: 20px 0;
  font-size: 16px;
  font-weight: 700;
}
</style>
<style lang="less">
.teacher-info {
  .ant-pagination {
    margin-top: 20px;
  }
}
</style>
